package com.ae.controller;

import com.ae.pojo.QueryVo;
import com.ae.pojo.Speaker;
import com.ae.service.SpeakerService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

/**
 * @Auther ys
 * @Date 2020/10/20
 * 9:54
 */
@Controller
@RequestMapping("speaker")
public class SpeakerController {

    @Autowired
    private SpeakerService speakerService;


    @RequestMapping("showSpeakerList")
    public String findByPage(@RequestParam(defaultValue = "1", required = false) Integer pageNum,
                             @RequestParam(defaultValue = "2", required = false) Integer pageSize,
                             Model model,
                             QueryVo queryVo) {

        model.addAttribute("queryVo", queryVo);

        if (pageNum < 1) {
            pageNum = 1;
        } else if (pageNum > getTotalPage()) {
            pageNum = getTotalPage();
        }

        PageHelper.startPage(pageNum,2);

        List<Speaker> speakers = speakerService.findAllSpeaker(queryVo);

        PageInfo<Speaker> speakerPageInfo = new PageInfo<>(speakers);
        model.addAttribute("speakerPageInfo",speakerPageInfo);
        return "/behind/speakerList.jsp";
    }

    public Integer getTotalPage() {
        Integer pageSize = 2;
        Integer totalCount = speakerService.getTotalCount();

        if (totalCount % pageSize == 0) {
            return totalCount / pageSize;
        } else {
            return (totalCount / pageSize) + 1;
        }
    }

    @RequestMapping("addSpeaker")
    public String addSpeaker() {
        return "/behind/addSpeaker.jsp";
    }

    @RequestMapping("edit")
    public String edit(Integer id, Model model) {

        Speaker speaker = speakerService.findById(id);
        model.addAttribute("speaker", speaker);
        return "/behind/addSpeaker.jsp";
    }

    @RequestMapping("saveOrUpdate")
    public String saveOrUpdate(Speaker speaker, Integer id) {

        if (id == null) {

            speakerService.addSpeaker(speaker);
        } else {

            speaker.setId(id);
            speakerService.updateSpeaker(speaker);
        }

        return "redirect:/speaker/showSpeakerList";
    }

    @ResponseBody
    @RequestMapping("delSpeakerById")
    public String deleteSpeaker(Integer id) {
        int flag = speakerService.deleteSpeaker(id);
        if (flag == 1) {
            return "success";
        } else {
            return "false";
        }
    }

}
